package com.roc.web.action.merinfo;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.roc.bean.AreaBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblInsInf;
import com.roc.pojo.TblMchtBankAccount;
import com.roc.pojo.TblMchtInf;
import com.roc.pojo.TblTermInf;
import com.roc.service.IExcelService;
import com.roc.service.IMerchantServices;
import com.roc.service.IRiskService;
import com.roc.service.IorgService;
import com.roc.service.area.IAreaService;
import com.roc.util.Constance;
import com.roc.util.DateUtil;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.MerinfoStatus;
import com.roc.util.constant.Role;
import com.roc.web.action.agent.MerinfoStatisticsAction;

@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/merinfo")
public class MerinfoExportAction extends PaginationBaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2424662934710954184L;

	static Logger logger = LogManager.getLogger(MerinfoExportAction.class);

	private Long psamCardStartNo;
	private Long psamCardEndNo;
	private Long totalNum;
	private MerinfoExportSearchCondtion searchCondition;

	private List<TblInsInf> orgList = new ArrayList<TblInsInf>();
	private List<Operators> riskList = new ArrayList<Operators>();

	private InputStream excelFile;
	private String excelName;

	@Autowired
	IPageService pagenitionService;

	@Autowired
	IExcelService excelService;
	
	@Autowired 
	IMerchantServices merchantServices;
	
	@Autowired
	IorgService orgService;
	@Autowired
	IRiskService  riskService;
	@Autowired
	IAreaService areaService;
	

	@Action(value = "merinfoExportInit", results = {
			@Result(name = "success", location = "/pages/merinfo/merinfoExport.jsp"),
			@Result(name = "error", location = "/error.jsp") }
	)
	public String merinfoExportInit() throws Exception {
		Operators loginOperator = (Operators) ActionContext.getContext()
				.getSession().get(Constant.SESSION_LOGIN_MERCHANT);
		
		if(!loginOperator.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode()) && !loginOperator.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode()) && !loginOperator.getRoleType().equals(Role.SYSTEM.getCode())){
			addActionError("此登陆账号没有权限");
			return ERROR;
		}
		 if(loginOperator.getRoleType().equals(Role.AGENT.getCode()) && !loginOperator.getAccountNo().equals("sdsyb")){
			 addActionError("无权限访问");
			 return ERROR;
		 }
		searchCondition = new MerinfoExportSearchCondtion();
		// 默认查询当天日期
		String today = Constance.currTime();
		searchCondition.setCrtMinDate(today);
		searchCondition.setCrtMaxDate(today);
		org(loginOperator);
		
		return SUCCESS;
	}

	@Action(value = "queryMerinfoExportList", results = { @Result(name = "success", location = "/pages/merinfo/merinfoExport.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	// 查询代理商统计信息
	public String queryMerinfoExportList() throws Exception {

		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.AGENT.getCode()) && !op.getAccountNo().equals("sdsyb")){
			 addActionError("无权限访问");
			 return ERROR;
		 }
		if (searchCondition == null) {
			searchCondition = (MerinfoExportSearchCondtion) getSearchConditionFromSession();
			if (searchCondition == null) {
				searchCondition = new MerinfoExportSearchCondtion();
			}
		}
		try {
			
			if(!op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode()) && !op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode()) && !op.getRoleType().equals(Role.SYSTEM.getCode())){
				addActionError("此登陆账号没有权限");
				return ERROR;
			}
			org(op);
			// 设置机构号
			List<TblInsInf> orgList= orgService.queryOrgList();
			searchCondition.setOrgCode(orgList.get(0).getInsIdCd());
			
		    int rows = pagenitionService.countSQL(searchCondition);
	    	searchRsList = pagenitionService.findAllSQL(searchCondition,
					calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
	    	
			List<TblMchtInf> opBeanList = new ArrayList<TblMchtInf>();
			if (searchRsList != null && searchRsList.size() > 0) {
				Iterator iterator = searchRsList.iterator();
				while (iterator.hasNext()) {
					Object[] obj = (Object[]) iterator.next();
					TblMchtInf bean = new TblMchtInf();
					
					TblMchtBankAccount bankAccount = new TblMchtBankAccount();
					TblTermInf termBean = new TblTermInf();
					List<TblTermInf> terminfoList = new ArrayList<TblTermInf>(); 
					
					if (obj[0] != null && !"".equals(obj[0])) {
						bean.setId(Constance.Null2EmptyTrim(obj[0]));
					}
					if (obj[1] != null && !"".equals(obj[1])) {
						bean.setBankBelongCd(Constance.Null2EmptyTrim(obj[1]));
					}
					if (obj[2] != null && !"".equals(obj[2])) {
						bean.setUcBccd(Constance.Null2EmptyTrim(obj[2]));
					}
					if (obj[3] != null && !"".equals(obj[3])) {
						bean.setMchcdAreadCd(Constance.Null2EmptyTrim(obj[3]));
					}
					if (obj[4] != null && !"".equals(obj[4])) {
						bean.setUpMccCd(Constance.Null2EmptyTrim(obj[4]));
					}
					if (obj[5] != null && !"".equals(obj[5])) {
						bean.setName(Constance.Null2EmptyTrim(obj[5]));
					}
					if (obj[6] != null && !"".equals(obj[6])) {
						bean.setNameBusi(Constance.Null2EmptyTrim(obj[6]));
					}
					if (obj[7] != null && !"".equals(obj[7])) {
						bean.setBusiLiceNo(Constance.Null2EmptyTrim(obj[7]));
					}
					if (obj[8] != null && !"".equals(obj[8])) {
						bean.setBusiRang(Constance.Null2EmptyTrim(obj[8]));
					}
					if (obj[9] != null && !"".equals(obj[9])) {
						bean.setBusiMain(Constance.Null2EmptyTrim(obj[9]));
					}
					if (obj[10] != null && !"".equals(obj[10])) {
						bean.setCertif(Constance.Null2EmptyTrim(obj[10]));
					}
					if (obj[11] != null && !"".equals(obj[11])) {
						bean.setCertifType(Constance.Null2EmptyTrim(obj[11]));
					}
					if (obj[12] != null && !"".equals(obj[12])) {
						bean.setCertifNo(Constance.Null2EmptyTrim(obj[12]));
					}
					if (obj[13] != null && !"".equals(obj[13])) {
						bean.setContactName(Constance.Null2EmptyTrim(obj[13]));
					} 
					if (obj[14] != null && !"".equals(obj[14])) {
						bean.setContactPhoneNo(Constance.Null2EmptyTrim(obj[14]));
					}
					if (obj[15] != null && !"".equals(obj[15])) {
						bean.setProvCd(Constance.Null2EmptyTrim(obj[15]));
					}
					if (obj[16] != null && !"".equals(obj[16])) {
						bean.setCityCd(Constance.Null2EmptyTrim(obj[16]));
					}
					if (obj[17] != null && !"".equals(obj[17])) {
						bean.setAreaCd(Constance.Null2EmptyTrim(obj[17]));
					}
					if (obj[18] != null && !"".equals(obj[18])) {
						bean.setRegAddr(Constance.Null2EmptyTrim(obj[18]));
					}
					if (obj[19] != null && !"".equals(obj[19])) {
						bankAccount.setName(Constance.Null2EmptyTrim(obj[19]));
					}
					if (obj[20] != null && !"".equals(obj[20])) {
						bankAccount.setAccount(Constance.Null2EmptyTrim(obj[20]));
					}
					if (obj[21] != null && !"".equals(obj[21])) {
						bankAccount.setBankName(Constance.Null2EmptyTrim(obj[21]));
					}
					if (obj[22] != null && !"".equals(obj[22])) {
						bankAccount.setBankCode(Constance.Null2EmptyTrim(obj[22]));
					}
					if (obj[23] != null && !"".equals(obj[23])) {
						termBean.getId().setTermId(Constance.Null2EmptyTrim(obj[23]));
					}

					if (obj[24] != null && !"".equals(obj[24])) {
						bean.setStlmWayDesc(Constance.Null2EmptyTrim(obj[24])); // 非法人身份证号
					}
					if (obj[25] != null && !"".equals(obj[25])) {
						bean.setDirectlyAgent(Constance.Null2EmptyTrim(obj[25])); // 直属代理商
					}
					
					if (obj[26] != null && !"".equals(obj[26])) {
						bean.setCompanyName(Constance.Null2EmptyTrim(obj[26])); // 所属分公司
					}
					if (obj[27] != null && !"".equals(obj[27])) {
						bean.setOneagentName(Constance.Null2EmptyTrim(obj[27])); // 一级代理商
					}
					if (obj[28] != null && !"".equals(obj[28])) {
						bean.setBus_lic(Constance.Null2EmptyTrim(obj[28])); // 审核人员
					}
					
					bean.setBankAccount(bankAccount);
					
					terminfoList.add(termBean);
					bean.setTerminfoList(terminfoList);
					opBeanList.add(bean);
				}
			}
		    
			searchRsList.clear();
			searchRsList.addAll(opBeanList);
			dealWithTheListSpecially(searchRsList);
			addActionMessage("当前条件下统计到【" + rows + "】条记录");
			
			this.setTotalPage(this.calcuTotalPage(rows));
			
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			
			List<Operators> oneAgengList = merchantServices.queryAllOneAgent(searchCondition.getAreaCode());
			getRequest().setAttribute("oneAgengList", oneAgengList);

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
		}

		return SUCCESS;
	}

	// 导出excel
	@Action(value = "excelMerinfoExportList", results = {
			@Result(name = "success", type = "stream", params = {
					"contentType", "application/vnd.ms-excel", "inputName",
					"excelFile", "contentDisposition",
					"attachment;filename=${excelName}.xls", "bufferSize",
					"1024*3" }),
			@Result(name = "error", location = "/pages/merinfo/merinfoExport.jsp") })
	public String settingExcelqQuery() throws Exception {
		try {
			
			Operators op = (Operators) ActionContext.getContext()
			.getSession().get(Constant.SESSION_LOGIN_MERCHANT);
			
			
			if (searchCondition == null) {
				searchCondition = (MerinfoExportSearchCondtion) getSearchConditionFromSession();
				if (searchCondition == null) {
					searchCondition = new MerinfoExportSearchCondtion();
				}
			}

			if(!op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode()) && !op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode()) && !op.getRoleType().equals(Role.SYSTEM.getCode())){
				addActionError("此登陆账号没有权限");
				return ERROR;
			}

			if(searchCondition.getCrtMinDate()==null || searchCondition.getCrtMinDate().trim().length() == 0){
				addActionError("请选择清算起始日期！");
				return ERROR;
			}
			if(searchCondition.getCrtMaxDate() == null || searchCondition.getCrtMaxDate().trim().length()==0){
				addActionError("请选择清算终止日期！");
				return ERROR;
			}
			
			int days = DateUtil.daysBetween(searchCondition.getCrtMinDate(),searchCondition.getCrtMaxDate());
			if(days > 9){
				addActionError("选择的起始时间相隔超过10天！");
				return ERROR;
			}
			
			// 设置机构号
			List<TblInsInf> orgList= orgService.queryOrgList();
			searchCondition.setOrgCode(orgList.get(0).getInsIdCd());

			List<TblMchtInf> opBeanList = new ArrayList<TblMchtInf>();
			
		    int rows = pagenitionService.countSQL(searchCondition);
		    if(rows > 0){
		    	searchRsList = pagenitionService.findAllSQL(searchCondition,
						calcuStart(getCurrentPage()), rows);
		    	
				if (searchRsList != null && searchRsList.size() > 0) {
					Iterator iterator = searchRsList.iterator();
					while (iterator.hasNext()) {
						Object[] obj = (Object[]) iterator.next();
						TblMchtInf bean = new TblMchtInf();
						
						TblMchtBankAccount bankAccount = new TblMchtBankAccount();
						TblTermInf termBean = new TblTermInf();
						List<TblTermInf> terminfoList = new ArrayList<TblTermInf>(); 
						
						if (obj[0] != null && !"".equals(obj[0])) {
							bean.setId(Constance.Null2EmptyTrim(obj[0]));
						}
						if (obj[1] != null && !"".equals(obj[1])) {
							bean.setBankBelongCd(Constance.Null2EmptyTrim(obj[1]));
						}
						if (obj[2] != null && !"".equals(obj[2])) {
							bean.setUcBccd(Constance.Null2EmptyTrim(obj[2]));
						}
						if (obj[3] != null && !"".equals(obj[3])) {
							bean.setMchcdAreadCd(Constance.Null2EmptyTrim(obj[3]));
						}
						if (obj[4] != null && !"".equals(obj[4])) {
							bean.setUpMccCd(Constance.Null2EmptyTrim(obj[4]));
						}
						if (obj[5] != null && !"".equals(obj[5])) {
							bean.setName(Constance.Null2EmptyTrim(obj[5]));
						}
						if (obj[6] != null && !"".equals(obj[6])) {
							bean.setNameBusi(Constance.Null2EmptyTrim(obj[6]));
						}
						if (obj[7] != null && !"".equals(obj[7])) {
							bean.setBusiLiceNo(Constance.Null2EmptyTrim(obj[7]));
						}
						if (obj[8] != null && !"".equals(obj[8])) {
							bean.setBusiRang(Constance.Null2EmptyTrim(obj[8]));
						}
						if (obj[9] != null && !"".equals(obj[9])) {
							bean.setBusiMain(Constance.Null2EmptyTrim(obj[9]));
						}
						if (obj[10] != null && !"".equals(obj[10])) {
							bean.setCertif(Constance.Null2EmptyTrim(obj[10]));
						}
						if (obj[11] != null && !"".equals(obj[11])) {
							bean.setCertifType(Constance.Null2EmptyTrim(obj[11]));
						}
						if (obj[12] != null && !"".equals(obj[12])) {
							bean.setCertifNo(Constance.Null2EmptyTrim(obj[12]));
						}
						if (obj[13] != null && !"".equals(obj[13])) {
							bean.setContactName(Constance.Null2EmptyTrim(obj[13]));
						} 
						if (obj[14] != null && !"".equals(obj[14])) {
							bean.setContactPhoneNo(Constance.Null2EmptyTrim(obj[14]));
						}
						if (obj[15] != null && !"".equals(obj[15])) {
							bean.setProvCd(Constance.Null2EmptyTrim(obj[15]));
						}
						if (obj[16] != null && !"".equals(obj[16])) {
							bean.setCityCd(Constance.Null2EmptyTrim(obj[16]));
						}
						if (obj[17] != null && !"".equals(obj[17])) {
							bean.setAreaCd(Constance.Null2EmptyTrim(obj[17]));
						}
						if (obj[18] != null && !"".equals(obj[18])) {
							bean.setRegAddr(Constance.Null2EmptyTrim(obj[18]));
						}
						if (obj[19] != null && !"".equals(obj[19])) {
							bankAccount.setName(Constance.Null2EmptyTrim(obj[19]));
						}
						if (obj[20] != null && !"".equals(obj[20])) {
							bankAccount.setAccount(Constance.Null2EmptyTrim(obj[20]));
						}
						if (obj[21] != null && !"".equals(obj[21])) {
							bankAccount.setBankName(Constance.Null2EmptyTrim(obj[21]));
						}
						if (obj[22] != null && !"".equals(obj[22])) {
							bankAccount.setBankCode(Constance.Null2EmptyTrim(obj[22]));
						}
						if (obj[23] != null && !"".equals(obj[23])) {
							termBean.getId().setTermId(Constance.Null2EmptyTrim(obj[23]));
						}

						if (obj[24] != null && !"".equals(obj[24])) {
							bean.setStlmWayDesc(Constance.Null2EmptyTrim(obj[24])); // 非法人身份证号
						}
						if (obj[25] != null && !"".equals(obj[25])) {
							bean.setDirectlyAgent(Constance.Null2EmptyTrim(obj[25])); // 直属代理商
						}

						if (obj[26] != null && !"".equals(obj[26])) {
							bean.setCompanyName(Constance.Null2EmptyTrim(obj[26])); // 所属分公司
						}
						if (obj[27] != null && !"".equals(obj[27])) {
							bean.setOneagentName(Constance.Null2EmptyTrim(obj[27])); // 一级代理商
						}
						if (obj[28] != null && !"".equals(obj[28])) {
							bean.setBus_lic(Constance.Null2EmptyTrim(obj[28])); // 审核人员
						}
						bean.setBankAccount(bankAccount);
						
						terminfoList.add(termBean);
						bean.setTerminfoList(terminfoList);
						opBeanList.add(bean);
					}
				}
		    }
			setExcelName(new String("商户信息导出".getBytes(), "ISO8859-1"));

			HSSFWorkbook work = excelService.exportMerinfoTransQueryExcel(opBeanList,searchCondition.getCrtMinDate(),searchCondition.getCrtMaxDate());
			ByteArrayOutputStream output = new ByteArrayOutputStream();  
			work.write(output);  
			   
			byte[] ba = output.toByteArray();  
			excelFile = new ByteArrayInputStream(ba);  
			output.flush();  
			output.close();
		} catch (Exception e) {
			logger.info("######商户信息导出Excel明细失败######");
			addActionError(e.getMessage());
			return ERROR;
		} 
		return SUCCESS;
	}

	// 加载数据
	public void org(Operators op) throws Exception{
		List<AreaBean> opList = new ArrayList<AreaBean>();
		opList = areaService.queryAreaInf(op);
		
		//初始化风控人员
		riskList = riskService.queryrisk();
		
		getRequest().setAttribute("opList", opList);
		getRequest().setAttribute("oneAgengList", new ArrayList<Operators>());
		getRequest().setAttribute("mcc", ConfigProperties.getHyMccTypeProperties());//mcc
	}
	
	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE + "";
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (MerinfoExportSearchCondtion) getSession().getAttribute(
				SEARCH_SESSION_BEAN_TERM_SN_IMPORT);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);

	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_BEAN_TERM_SN_IMPORT,
				searchCondition);
	}

	public Long getPsamCardStartNo() {
		return psamCardStartNo;
	}

	public void setPsamCardStartNo(Long psamCardStartNo) {
		this.psamCardStartNo = psamCardStartNo;
	}

	public Long getPsamCardEndNo() {
		return psamCardEndNo;
	}

	public void setPsamCardEndNo(Long psamCardEndNo) {
		this.psamCardEndNo = psamCardEndNo;
	}

	public Long getTotalNum() {
		return totalNum;
	}

	public void setTotalNum(Long totalNum) {
		this.totalNum = totalNum;
	}

	public List<TblInsInf> getOrgList() {
		return orgList;
	}

	public void setOrgList(List<TblInsInf> orgList) {
		this.orgList = orgList;
	}

	public MerinfoExportSearchCondtion getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(MerinfoExportSearchCondtion searchCondition) {
		this.searchCondition = searchCondition;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

	public String getExcelName() {
		return excelName;
	}

	public void setExcelName(String excelName) {
		this.excelName = excelName;
	}

	public List<Operators> getRiskList() {
		return riskList;
	}

	public void setRiskList(List<Operators> riskList) {
		this.riskList = riskList;
	}



}
